package com.xiaotu.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.impl.PublicClaims;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class TokenUtil {

    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    private static final String TOKEN_SECRET = "life is a fucking movie";  //密钥盐

    /**
     * 签名生成
     *
     * @param jsonStr
     * @return
     */
    public static String createToken(String jsonStr) {
        String token = null;
        try {
            /**
             * 30 天过期时间
             */
            Date expiresAt = new Date(System.currentTimeMillis() + 30 * EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0")
                    .withSubject(jsonStr)
                    .withExpiresAt(expiresAt)
                    //使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 签名验证
     *
     * @param token
     * @return
     */
    public static boolean verifyToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            log.info("过期时间：" + DateUtil.format(jwt.getExpiresAt(), DateUtil.PATTERN_SYSTEM_DEFAULT));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取全局缓存
     *
     * @return
     */
    public static <T> T getGloGlobalCache(HttpServletRequest request, String key, Class<T> tClass) {
        String token = getCookie(request);
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
        DecodedJWT jwt = verifier.verify(token);
        String jsonStr = jwt.getClaim(PublicClaims.SUBJECT).asString();
        Map<String, Object> map = JSONArray.parseObject(jsonStr, Map.class);
        return (T) ((JSONObject) map.get(key)).toJavaObject(tClass);
    }

    public static String getCookie(HttpServletRequest request) {
        String cookie = request.getHeader("token");
        return cookie;
    }

    /**
     * 负载
     */
    public static class PayloadData {

        private static final Map<String, Object> PAYLOAD_DATA = new HashMap<>();

        public static void setKeyVal(String key, Object val) {
            PAYLOAD_DATA.put(key, val);
        }

        public static String toJson() {
            return JSONArray.toJSON(PAYLOAD_DATA).toString();
        }

    }

}